local modname = minetest.get_current_modname()
-- local modpath = minetest.get_modpath(modname)
local S = minetest.get_translator(modname)


-- --------------------------------------------------

-- Farmers
--
-- Farmers look for crops that are ready to harvest and replace them with seed
--
----- TODO:
-- -- They key their recolt in a small inventory
-- -- If given a key for a locked chest,
-- --  they will go and put their harvest in the chest once they are out of space
-- -- They stay near straw blocks
-- --

-- dofile(modpath..'/dialogs/farmer.lua')

-- local mcl = minetest.get_modpath("mcl_core") ~= nil
-- local drop_trade_item = (mcl and "mcl_raw_ores:raw_gold" or "default:gold_lump")

local mobname = 'farmer'

local mobs_griefing = minetest.settings:get_bool("mobs_griefing") ~= false
local farming_is_not_griefing = minetest.settings:get_bool("mobs_npc.farming_is_not_griefing", true)

-- Maybe this should be a global function ?
local function npc_farm (self, dtime)

  -- Respect griefing setting with possible farming exeption
  if not ( mobs_griefing or farming_is_not_griefing ) then return end

  -- Can't harvest anything on a full inventory
  if self.inventory_full then return end

  -- farming_rate of 10 means mob will try to farm 1 out of 10 ticks
  local farming_rate = self.farming_rate
  if not farming_rate or math.random(farming_rate) > 1 then return end

  -- Ensure that mob is not recovering from an attack
  if self.env_damage_timer > 1 then return end

  -- Check that self.farming_what must be set to a nested table
  local replace_what = self.farming_what
  if not replace_what then return end
  if type(replace_what) ~= "table" then return end
  if type(replace_what[1]) ~= "table" then return end

  -- Get one random element in the list of things to farm
  -- and set what, with, and offset from it
  local what, with, y_offset
  local num = math.random(#replace_what)
  what = replace_what[num][1] or ""
  with = replace_what[num][2] or ""
  y_offset = replace_what[num][3] or 0

  -- Look for what node at pos
  local pos = self.object:get_pos()
  pos.y = pos.y + y_offset
  if #minetest.find_nodes_in_area(pos, pos, what) > 0 then

    -- Stop moving, no one is harvesting crops while running
    self.state = "stand"
    self:set_animation("stand")
    self:set_velocity(0)

    -- Do we want to do self.on_replace there ?
    -- if self.on_replace then
      -- local oldnode = what or ""
      -- local newnode = with
      -- --- pass actual node name when using table or groups
      -- if type(oldnode) == "table" or oldnode:find("group:") then
        -- oldnode = minetest.get_node(pos).name
      -- end
      -- if self:on_replace(pos, oldnode, newnode) == false then
        -- return
      -- end
    -- end

    if mobs_npc.enable_inventory then
      -- Add harvest to inventory
      local inv = mobs_npc.get_npc_inventory(self)
      local wielded = mobs_npc.get_npc_wield_item(self, inv)
      local toolname
      if wielded then toolname = wielded:get_name() end
      local drops = minetest.get_node_drops(what, toolname)
      for _,drop in ipairs(drops) do
        if inv:room_for_item('main', drop) then
          inv:add_item('main', drop)
        else
          self.inventory_full = true
        end
      end
      -- Item to replace with is not placed unless we can take it from the inventory
      -- TODO: Maybe don't try to farm at all in that case ?
      if not inv:contains_item('main', with) then with = 'air'
      else inv:remove_item('main', with)
      end
    end

    -- Setting param 2 to ensure seeds are placed on the ground
    local with_def = {name=with}
    if with ~= 'air' then
      with_def.param2 = minetest.dir_to_wallmounted({x=0,y=-1,z=0})
    end

    -- Actually replace the node (finally)
    minetest.set_node(pos, with_def)

  end

end

-- Local farming items
local jobs = {
  -- {
    -- farming_what = { <what>, <with>, <offset>},
  -- },
  {
    farming_what = {"farming:wheat_8", "farming:seed_wheat", -1},
  },
  {
    farming_what = {"farming:cotton_8", "farming:seed_cotton", -1},
  }
}

local def = mobs_npc.default_npc_def()
def.name = modname .. ':'..mobname
def.job = 'farmer'
def.stay_near = {
    {"farming:wheat_8"},
    10
  }

def.on_spawn = function(self)
  local num = math.random(#jobs)
  local job = jobs[num]
  if job and job.farming then
    self.farming_what = {                             -- like replace_what nested arrays
      job.farming_what
    }
    table.insert(self.stay_near[1], job.farming_what[1])
    self.farming_rate = 10
  end
  return true -- true to run only once
end

def.do_custom = function(self, dtime)
  npc_farm(self, dtime)
end


mobs:register_mob(def.name, def)
mobs:register_egg(def.name, S("Farmer"), "default_gold_block.png", 1)
mobs:alias_mob("mobs:"..mobname, def.name)
